package fr.starn.meteo_widgets;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import android.content.Context;
import ch.boye.httpclientandroidlib.HttpEntity;
import ch.boye.httpclientandroidlib.HttpHost;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.HttpClient;
import ch.boye.httpclientandroidlib.client.methods.HttpGet;
import ch.boye.httpclientandroidlib.client.params.ClientPNames;
import ch.boye.httpclientandroidlib.conn.ClientConnectionManager;
import ch.boye.httpclientandroidlib.conn.scheme.Scheme;
import ch.boye.httpclientandroidlib.conn.scheme.SchemeRegistry;
import ch.boye.httpclientandroidlib.conn.ssl.SSLSocketFactory;
import ch.boye.httpclientandroidlib.impl.client.AbstractHttpClient;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;
import ch.boye.httpclientandroidlib.params.BasicHttpParams;
import ch.boye.httpclientandroidlib.params.HttpConnectionParams;
import ch.boye.httpclientandroidlib.params.HttpParams;
import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
import ch.boye.httpclientandroidlib.util.EntityUtils;
import fr.starn.meteo_widgets.JSonObject.DevicesProps;


public class RestRequestHandler implements Runnable{
	
	
	private WidgetPropertiesBean connectionProp;
	private Context context;
	private IValueReceiver parent;
	
	private static final long cacheDuration = 1000*60*20;//20 minutes
	
	
	/**
	 * constructor to get values
	 */
	public RestRequestHandler(Context context, IValueReceiver parent, WidgetPropertiesBean connectionProp){
		this.context=context;
		this.parent=parent;
		this.connectionProp=connectionProp;
	}
	


	
	public void run(){

		getTemp();
	}
	
	public void getTemp(){
		try {
			//cache.clear();
			//refresh light status
	        String request = "/data/2.5/weather?q="+connectionProp.getTown().replaceAll(" ","%20");
			//String request = "/weather/?q="+connectionProp.getTown().trim().replaceAll(" ","%20");
	        String content = null;
        	content = launchHttpRequest("api.openweathermap.org",request);
	        //content = launchHttpRequest("stephane-arnault.net",request);
	        DevicesProps jsonProps =DevicesProps.deserialize(content);
	        String country = jsonProps.getSys().getCountry();
	        System.out.println(country);
	        parent.updateValue(context, connectionProp, jsonProps);
		} catch (Exception e){
			
			e.printStackTrace();
			parent.manageError(context, connectionProp, e.getMessage());
		}
	}
	
	
	
		
	
	private String launchHttpRequest(String host, String request) throws Exception{
//		long currenttime=new Date().getTime();

		
        final HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, 10000);//10 seconds
        HttpClient defaultHttpClient = new DefaultHttpClient(httpParams);
        
		AbstractHttpClient client = wrapClient(defaultHttpClient);
		client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, true);
		
        
        BasicHttpContext localContext = new BasicHttpContext();
        
        HttpHost targetHost = new HttpHost(host,80);
        System.out.println("exec req:"+request);
        HttpGet httpget = new HttpGet(request);
        httpget.setHeader("Content-Type", "application/xml");
        
        HttpResponse response = client.execute(targetHost, httpget,
                localContext);
        if (response.getStatusLine().getStatusCode()==401){
        	System.err.println("401 bad auth");
        	throw new Exception("401 bad auth");
        }
        if (response.getStatusLine().getStatusCode()==404){
        	System.err.println("404 not found");
        	throw new Exception("404 not found");
        }
        HttpEntity entity = response.getEntity();
        String content = EntityUtils.toString(entity);

        return content;
	}
	

	
	
	private static AbstractHttpClient wrapClient(HttpClient base) {
		try {
			SSLContext ctx = SSLContext.getInstance("TLS");
			X509TrustManager tm = new X509AlwaysTrust();

			ctx.init(null, new TrustManager[] { tm }, null);
			SSLSocketFactory ssf = new SSLSocketFactory(
					ctx);
			ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
			ClientConnectionManager ccm = base.getConnectionManager();
			SchemeRegistry sr = ccm.getSchemeRegistry();
			sr.register(new Scheme("https", ssf, 443));
			return new DefaultHttpClient(ccm, base.getParams());
		} catch (Exception ex) {
			ex.printStackTrace();
			return null;
		}
	}








}
